// pages/cart/index.js
const service = require('../../service/port.js')
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast.js';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    cartArray: [],
    totalMoney: '0.00', // 金额总计
    totalCount: 0, // 结算商品数量总和
    selectAll: false, // 是否全选
    startX: 0, //开始坐标
    startY: 0,
    checkAll: false,
  },

  setAccount: function () {

    let shoppingList = [];
    
    this.data.cartArray.forEach(cart => {
      if (cart.select) {
        shoppingList.push(cart)
      }
    })
    if(shoppingList.length==0){
      Toast.fail("请选择商品！")
      return
    }
    // const accountInfo = {
    //   shoppingList: shoppingList,
    //   totalMoney: this.data.totalMoney
    // }

    // // 跳转
    // wx.navigateTo({
    //   url: '/pages/order/createOrder/index?accountInfo=' + JSON.stringify(accountInfo)
    // })

    this.toFinalConfirmOrder(shoppingList)
  },


  toFinalConfirmOrder (shoppingList) {
  
    let totalMoney = Number(this.data.totalMoney) * 100
   
    let orderInfo = {
      type: '6',
      shoppingList: shoppingList,
      totalMoney: totalMoney,
    }
    
    console.log('orderInfo===========')
    console.log('购物车',orderInfo)
    console.log('orderInfo===========')
    orderInfo = JSON.stringify(orderInfo)
    wx.navigateTo({
      url: `/pages/order/finalComfirmOrder/index?orderInfo=${orderInfo}`,
    })
  },


  initData() {

  },

  onShow: function () {
    var self = this;
    let userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return;
    wx.showLoading({
      title: '加载中',
    })
    service.cartList(userInfo.id, res => {

      let tempList = []
      let tbShoppingcartList = res.data
      tempList = [...tbShoppingcartList]
      tempList.forEach(item => {
        item.select = false
        item.isTouchMove = false
      })
      // activityList.forEach(tb => {
      //   let temp = {
      //     name: '',
      //     isActivity: true,
      //     children: []
      //   }
      //   tb.forEach(item => {
      //     item.select = false
      //     item.isTouchMove = false
      //     temp.name = item.setmealName
      //     temp.children.push(item)
      //   })
      //   tempList.push(temp)
      // })
      wx.hideLoading()

      this.setData({
        cartArray: tempList,
      })
    })
    self.setData({
      cartArray: this.data.cartArray,
      selectAll: false,
      totalMoney: '0.00',
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 更新Storage
    const cartArray = this.data.cartArray;
    wx.setStorage({
      key: 'cartInfo',
      data: cartArray
    });
  },
  /**
   * 子组件修改count触发
   */
  onGetCount: function (e) {
    console.log(e);
    const start = e.currentTarget.dataset.start;
    const index = e.currentTarget.dataset.index;
    const cartArray = this.data.cartArray;
    if (start === undefined) {
      cartArray[index].num = e.detail.val;
    } else {
      cartArray[start].children[index].num = e.detail.val;
    }
    this.computedMondy(cartArray)
  },
  /**
   * 点击进入详情页面
   */
  switchGoodDetail(e) {
    console.log(e)
    wx.navigateTo({
      url: '/pages/product/productDetail/index?id=' + e.currentTarget.dataset.item.spuId
    });
  },
  /**
   * 选中单个商品
   */
  selectGood(e) {
    const start = e.currentTarget.dataset.start;
    const index = e.currentTarget.dataset.index;
    let cartArray = this.data.cartArray;
    // 设置选中或不选中状态
    if (start === undefined) {
      cartArray[index].select = !cartArray[index].select;
    } else {
      cartArray[start].children[index].select = !cartArray[start].children[index].select;
    }
    this.computedMondy(cartArray)
  },
  /**
   * count -1
   */

  computedMondy(cartArray, totalMoney = 0) {
    if (!cartArray) cartArray = this.data.cartArray;
    setTimeout(() => {
      cartArray.forEach(item => {
        if (item.isActivity === true) {
          item.children.forEach(item2 => {
            if (item2.select) totalMoney += item2.priceFen * item2.num
          })
        } else {
          if (item.select) totalMoney += item.priceFen * item.num
        }
      })
      this.setData({
        totalMoney: totalMoney.toFixed(2),
        cartArray: cartArray
      })
    }, 0)

  },
  subCount(e) {
    console.log(e)
    wx.showLoading({
      title: '加载中',
      icon:"none"
    })
    service.updateCartInfo({
      "id": e.currentTarget.dataset.item.id,
      "customerId": wx.getStorageSync('userInfo').id,
      "spuId": e.currentTarget.dataset.item.spuId,
      "skuId": e.currentTarget.dataset.item.skuId,
      "num": e.currentTarget.dataset.item.num-1
    }, res => {
      wx.hideLoading();
      console.log(res)
    })
    const cartArray = this.data.cartArray;
    this.computedMondy(cartArray)

  },
  sub2Count(e) {
    const start = e.currentTarget.dataset.start;
    const index = e.currentTarget.dataset.index;
    const cartArray = this.data.cartArray;
    cartArray[start].children[index].num--;
    this.computedMondy(cartArray)
  },

  addCount(e) {
    console.log(e);
    wx.showLoading({
      title: '加载中',
      icon:"none"
    })
    service.updateCartInfo({
      "id": e.currentTarget.dataset.item.id,
      "customerId": wx.getStorageSync('userInfo').id,
      "spuId": e.currentTarget.dataset.item.spuId,
      "skuId": e.currentTarget.dataset.item.skuId,
      "num": e.currentTarget.dataset.item.num+1
    }, res => {
      wx.hideLoading();
      console.log(res)
    })
    const cartArray = this.data.cartArray;
    this.computedMondy(cartArray)
  },
  add2Count(e) {
    const cartArray = this.data.cartArray;
    const start = e.currentTarget.dataset.start;
    const index = e.currentTarget.dataset.index;
    cartArray[start].children[index].num++;
    this.computedMondy(cartArray)
  },
  /**
   * 全选
   */
  selectAll(event) {

    this.setData({
      checkAll: event.detail,
    });
    const cartArray = this.data.cartArray;
    let selectAll = this.data.selectAll;
    selectAll = !selectAll; // 全选按钮置反

    cartArray.forEach(item => {
      if (item.isActivity === true) {
        item.children.forEach(item2 => {
          item2.select = selectAll
        })
      } else {
        item.select = selectAll
      }
    });
    this.computedMondy(cartArray)
    this.setData({
      selectAll: selectAll,
      checkAll: selectAll
    })

  },
  /**
   * 手指触摸动作开始 记录起点X坐标
   */
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.cartArray.forEach(function (v, i) {
      if (v.isTouchMove) {
        //只操作为true的
        v.isTouchMove = false;
      } else if (v.isActivity) {
        v.children.forEach(item => {
          if (item.isTouchMove) {
            //只操作为true的
            item.isTouchMove = false;
          }
        })
      }


    });
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      cartArray: this.data.cartArray
    });
  },
  /**
   * 滑动事件处理
   */
  touchmove: function (e) {
    let start = e.currentTarget.dataset.start
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });

    let cartArray = this.data.cartArray;
    // cartArray.forEach(item => {
    //   item.isTouchMove = false
    //   if (item.isActivity) {
    //     item.children.forEach(item2 => {
    //       item2.isTouchMove = false
    //     })
    //   }
    // })

    if (Math.abs(angle) > 30) return;
    if (start === undefined) {
      if (touchMoveX > startX) {
        cartArray[index].isTouchMove = false;
      } else {
        cartArray[index].isTouchMove = true;
      }
    } else {
      if (touchMoveX > startX) {
        cartArray[start].children[index].isTouchMove = false;
      } else {
        cartArray[start].children[index].isTouchMove = true;
      }
    }

    this.setData({
      cartArray: cartArray
    })
  },
  /**
   * 计算滑动角度
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y;
    //返回角度 /Math.atan()返回数字的反正切值
    return (360 * Math.atan(_Y / _X)) / (2 * Math.PI);
  },

  /**
   * 删除事件
   */
  del: function (e) {
    let start = e.currentTarget.dataset.start;
    var index = e.currentTarget.dataset.index;
    var self = this;
    service.deleteCart(e.currentTarget.dataset.item.id, res => {
      self.update(start, index);
      Toast.success('删除成功');
    })
  },
  update: function (start, index) {
    var cartArray = this.data.cartArray;
    if (start === undefined) {
      cartArray.splice(index, 1);
    } else {
      cartArray[start].children.splice(index, 1);
    }
    this.computedMondy(cartArray)
  },
  onHide: function () {
    this.setData({
      selectAll: false,
      checkAll: false
    })
  },
});